<template>
	<view>
		<view class="padding flex flex-direction">
			<block v-if="bleDeviceError">
				<view class="flex-sub text-center">
					<view class="solid-bottom text-xl padding">
						<text class="text-black text-bold">未连接蓝牙设备请先搜索蓝牙</text>
					</view>
				</view>
			</block>
			<block v-if="bleDevice">
				<view class="flex-sub text-center">
					<view class="solid-bottom text-xl padding">
						<text class="text-black text-bold">当前设备：{{bleDevice && bleDevice.name}}</text>
					</view>
				</view>
			</block>
            
            
            <!-- 打印小票上面需列明的信息：条形码，，，、、、品名，货物件数，到付（还是已付，代收）、备注 -->
            
            <view style="padding-top: 30rpx;">编码：{{data.out_trade_no}}</view>
            <view>日期：{{data.start_date}}</view>
            <view>客户姓名：{{data.shipper_contact}}</view>
            <view>收货地址：{{data.destination}}</view>
            <view>联系电话：{{data.recipient_phone}}</view>
            <view v-if="data.pay_status">到付：{{(data.pay_status==1)?'未支付':'已支付'}}</view>
            <view v-if="data.remark">备注：{{data.remark}}</view>
            <view v-for="(item,index) in shop" :key="index">
                <view>品名：{{item.goods}}</view>
                <view>货物件数：{{item.send_num}}</view>
            </view>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="textTap">开始打印</button>
            
		<!-- 	<button class="cu-btn bg-blue margin-tb-sm lg" @tap="textSpacingTap">打印间距文本</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="text270Tap">打印竖排文本</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="qrcodeTap">打印二维码</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="BarcodeTap">打印无文本一维码</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="BarcodeTextTap">打印有文本一维码</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="labelTap">综合案例</button>
			<button class="cu-btn bg-blue margin-tb-sm lg" @tap="imageTap">打印位图</button>
			<canvas canvas-id="imageCanvas" id="imageCanvas" class="imageCanvas" :style="{width:width+'px',height:height+'px'}"></canvas> -->
		</view>


		<view class="canui-load" @touchmove.stop="catchtouchmove" v-if="loadModal">
			<view class='cu-load load-modal' v-if="loadModal">
				<!-- <image src='../../images/logo_gongsi@2x.png' style="width:136rpx;height:76rpx;margin-top:20rpx" mode='aspectFit'> -->
				<!-- </image> -->
				<view>打印中...</view>
			</view>
		</view>
        
	</view>
</template>

<script>
import putyEscUtils from '../static/js/putyEscUtils';
import putyBleUtils from '../static/js/putyBleUtils';
import printease from 'printease'


import {alert,showLoad,hideLoad} from '../static/js/putyBaseUtils';
export default {
	data() {
		return {
			bleDeviceError: false, //是否连接蓝牙报错
			bleDevice: null, //设备信息
			loadModal: false, //加载框
			width:400,
			height:320,
            data:'',
            shop:''
		}
	},
	onLoad(option) {
        console.log(option)
        this.data = option;
        this.shop =JSON.parse(option.data)
		this.createBLEConnection();
	},
	/**
	 * 监听页面卸载
	 */
	onUnload: function() {
		//关闭蓝牙模块
		putyBleUtils.closeBluetoothAdapter();
	},
	methods: {
        
        
		//打印文本
		async textTap() {
			this.initSendData();
			this.loadModal = true;
            let _this = this
            
            
			try {
				// let cmd = putyEscUtils.init(48).text("普贴打印").next().put()
				// let res = await putyBleUtils.printEsc(cmd);
                console.log(_this.data)
                let Arry = []
                let tspl = new printease.tspl.TsplLib()
                
                   tspl.init()
                   tspl.setEncoding('GB18030')
                   tspl.stringToCharCodeArray('100,80')
                   tspl.setSize(100, 80)
                   tspl.setSound(100, 80)
                   tspl.setBar(0,0,100,100)
                   tspl.setCls(5)
                   
                   
                   tspl.setQRCode(0,40, 'L', 8, 'A', 0, _this.data.out_trade_no)
                   tspl.setText(190,40,'3',0,1,1,'编码'+_this.data.out_trade_no)
                   tspl.setText(190,70,'3',0,1,1,'日期'+_this.data.start_date)
                   tspl.setText(190,100,'3',0,1,1,'客户姓名'+_this.data.shipper_contact)
                   tspl.setText(190,130,'3',0,1,1,'收货地址'+_this.data.destination)
                   tspl.setText(190,160,'3',0,1,1,'联系电话'+_this.data.recipient_phone)
                   
                   if(_this.data.pay_status==1){
                       tspl.setText(190,190,'3',0,1,1,'支付:未支付')
                   }else{
                       tspl.setText(190,190,'3',0,1,1,'支付:已支付')
                   }
                   
                   if(_this.data.remark){
                       tspl.setText(0,220,'3',0,1,1,'备注:'+_this.data.remark);
                   }
                   let key = 0
                   _this.shop.forEach((item,index)=>{
                       tspl.setText(0,250+(index*30),'3',0,1,1,'品名:'+item.goods+' 货物件数:'+item.send_num );
                       key = index
                   })
                   // tspl.setQRCode(0, 80, 'L', 5, 'A', 0, '11111')
                   tspl.setPrint(1)
                   let rst = putyBleUtils.printEsc(tspl.command);
                   
                   alert("打印完成")
                   
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		/**
		 * 连接设备
		 */
		async createBLEConnection() {
            console.log('连接中')
            let _this = this
			showLoad("连接设备中")
			try {
                console.log(1111)
				let bleDevice = uni.getStorageSync('bleDevice');
                console.log(bleDevice)
				if (bleDevice) {
					let res = await putyBleUtils.createBLEConnection(bleDevice.deviceId, bleDevice.name)
					_this.bleDeviceError = false;
					_this.bleDevice = bleDevice;
				} else {
					_this.bleDeviceError = true;
					_this.bleDevice = null;
				}
			} catch (error) {
				alert(error)
				_this.bleDeviceError = true;
				_this.bleDevice = null;
			}
			hideLoad();
		},
		/**
		 * 初始化
		 */
		initSendData() {
			const {
				bleDeviceError,
				bleDevice
			} = this;
			if (bleDeviceError || !bleDevice) {
				alert("未连接设备");
				throw new Error("未连接设备")
			}
		},
		//打印间距文本
		async textSpacingTap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(48).spacing(20).text("普贴打印").next().put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//打印竖排文本
		async text270Tap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(48).rotate(true).lineHeight(3).text("普\r\n贴\r\n打\r\n印").next().put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//打印无文本一维码
		async BarcodeTap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(48).BarCode(73, 2, 15, 0, "123456789104").next().put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//打印有文本一维码
		async BarcodeTextTap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(48).BarCode(73, 2, 15, 2, "123456789104").next().put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//打印二维码
		async qrcodeTap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(48).qrcode("12345678", 10, 3).next().put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//综合案例
		async labelTap() {
			this.initSendData();
			this.loadModal = true;
			try {
				let cmd = putyEscUtils.init(46)
					.printAlign(1)
					.fontWeight(true)
					.fontSize(0x11)
					.lineHeight(6)
					.text("普贴打印")
					.fontWeight(false)
					.fontSize(0)
					.lineHeight(5)
					.enter()
					.printWhiteLine(2)
					.printAlign(0)
					.text("产品名称：PT-50DC")
					.enter()
					.text("产品价格：￥123")
					.printAlign(1)
					.enter()
					.BarCode(73, 2, 5, 2, "123456789104")
					.next()
					.put()
				let res = await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			} catch (error) {
				alert(error)
			}
			this.loadModal = false;
		},
		//canvas基础绘制
		async canvasInit(){
			return new Promise((resolve) => {
				const id = 'imageCanvas'
				var ctx = uni.createCanvasContext(id)
				ctx.setFontSize(24)
               
                ctx.drawImage('https://shop.ccpingtai.cn/20220528095349.png',40,40,150,150)
                
                ctx.fillText('图片x40Y20 150*150', 40,260)
                ctx.fillText('画布400*320', 40,290)
                
                
                ctx.draw()
                
				resolve({id,width:this.width,height:this.height})
			})
		},
		async canvasGetImageData(canvas){
			return new Promise((resolve,reject) => {
				uni.canvasGetImageData({
					canvasId: canvas.id,
					x: 0,
					y: 0,
					width: canvas.width,
					height: canvas.height,
					complete: (res) => {
						resolve(res.data)
					}
				})
			})
		},
		//打印位图
		async imageTap(){
			this.initSendData();
			this.loadModal = true;
			let canvas = await this.canvasInit();
            
			try{
				let imageData = await this.canvasGetImageData(canvas);
				let cmd = putyEscUtils.init(48).image(imageData,canvas.width,canvas.height).next().put()
				await putyBleUtils.printEsc(cmd);
				alert("打印完成")
			}catch(error){
				alert(error)
			}
			this.loadModal = false;
		}
	}
}
</script>

<style scoped>
/*外层容器，防止穿透点击*/
.canui-load{
	position:fixed;
	width: 100%;
	height: 100%;
	top:0;
	left:0;
	background: rgba(0, 0, 0, 0.5);
	z-index:99999;
}
/*关闭设置的阴影层，关闭底部距离，让它居中*/
.canui-load .cu-load.load-modal{
	box-shadow:inherit;
	bottom:0;
}
/*修改加载圈圈颜色*/
.canui-load .cu-load.load-modal::after{
	border-left: 6rpx solid #0081ff;
}
</style>
